import { useCallback, useLayoutEffect, useRef } from 'react';

// React useEvent RFC polyfill
const useEvent = <T extends (...args: any) => any>(handler: T) => {
  const handlerRef = useRef<T>();

  useLayoutEffect(() => {
    handlerRef.current = handler;
  });

  return useCallback((...args: Parameters<T>): ReturnType<T> => {
    const fn = handlerRef.current;
    return fn && fn(...args as any);
  }, []);
};

export default useEvent;
